﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Windows.Threading;


using Qplus.enums;
using Qplus.beans;
using Qplus.protocol;
using Qplus.Infrastructure;


namespace Qplus.protocol
{
    public class KeepAlive
    {
        private static KeepAlive instance;

        public static DispatcherTimer tmr;
        public static KeepAlive getInstance()
        {
            if (instance == null)
            {
                instance = new KeepAlive();
                tmr = new DispatcherTimer();//创建计时器
            }
            return instance;
        }

        public void startKeepAlive()
        {
            //System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => tmr = new DispatcherTimer());
            tmr.Interval = TimeSpan.FromSeconds(10);//TimeSpan 结构  表示一个时间间隔。
            tmr.Tick += OnTimerTick;//DispatcherTimer.Tick 事件 超过计时器间隔时发生。 
            tmr.Start();//计时器开始
        }

          

        public Boolean startNotifycommand()
        {
            MessageID MID = new MessageID();
            MID.setBody(MMessageID.C2U_NOTIFY_CLIENT_ONLINE);
            C2U_NOTIFY_CLIENT_ONLINE p = (C2U_NOTIFY_CLIENT_ONLINE)MID.getBody();
            p.sendKeepAlive();

            ConnectionManager.getInstance().send(p);

            return true;
        }

        public Boolean stopKeepAlive()
        {
            tmr.Stop(); //计时器停止
            return true;
        }

        //计时器触发的事件函数
        void OnTimerTick(object sender, EventArgs e)
        {
            Boolean res = startNotifycommand();

            if (res) { }
            else
                Debug.WriteLine("send a C2U_NOTIFY_CLIENT_ONLINE command Stoped!");
        }
    }
}
